﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using FairyGUI;

namespace Model
{
    [ObjectEvent]
    public class FGuiComponentEvent : ObjectEvent<FGuiComponent>, IAwake
    {
        public void Awake()
        {
            Get().Start();
        }
    }

    public class FGuiComponent : Component
    {
        public static FGuiComponent Single;
        Dictionary<UIViewType, GameUIView> dic = new Dictionary<UIViewType, GameUIView>();
        List<string> LoadPackage=new List<string>();
        string PackagePath="FGUI/";
        public GameUIView NowSence;
        public void Start()
        {
            Single = this;
            AddSence();            
            LoadSence(UIViewType.Login);
        }

        public GameUIView GetView(UIViewType type)
        {
            return dic[type];
        }

        public void LoadPackge(string PackageName)
        {
            if (LoadPackage.Contains(PackageName))
                return;
            LoadPackage.Add(PackageName);
            UIPackage.AddPackage(PackagePath + PackageName);
        }

        public void LoadSence(UIViewType type)
        {
            NowSence?.Leave();
            dic[type].Enter();
            NowSence = dic[type];
        }

        void AddSence()
        {
            Type[] types = DllHelper.GetMonoTypes();
            foreach (Type type in types)
            {
                object[] attrs = type.GetCustomAttributes(typeof(GameUIViewAttribute), false);

                foreach (object attr in attrs)
                {
                    GameUIViewAttribute aEventAttribute = (GameUIViewAttribute)attr;
                    object obj = Activator.CreateInstance(type);
                    if (!dic.ContainsKey(aEventAttribute.Type))
                    {
                        dic.Add(aEventAttribute.Type, (GameUIView)(obj));
                    }
                    else
                    {
                        Log.Error($"已存在相同的页面:{aEventAttribute.Type}");
                    }
                    //this.allEvents[(EventIdType)aEventAttribute.Type].Add(new IEventMonoMethod(obj));
                }
            }
            //Log.Debug(dic.Count.ToString());
        }
    }
}